package easy;

/**
 * Created by daodao on 2017/11/30.
 * Problem 14
 * Description: Write a function to find the longest common prefix string amongst an array of strings.
 */
public class LongestCommonPrefix {
    public static String longestCommonPrefix(String[] strs) {
        String commonPrefix = "";
        if (strs.length == 0) {
            return commonPrefix;
        }
        String firstStr = strs[0];
        int prefixLen = 0;
        if (!firstStr.isEmpty()) {
            int i;
            while (prefixLen <= firstStr.length()) {
                for (i = 1; i < strs.length; i++) {
                    if (prefixLen <= strs[i].length()) {
                        if (!firstStr.substring(0, prefixLen).equals(strs[i].substring(0, prefixLen))) {
                            break;
                        }
                    } else {
                        break;
                    }
                }
                if (i < strs.length) {
                    break;
                } else {
                    prefixLen++;
                }
            }
            commonPrefix = firstStr.substring(0, prefixLen - 1);
        }
        return commonPrefix;
    }
}
